
const querystring = require('querystring')
const handleBlogRouter = require('./router/blog')
const getData = (req, res) => {
    const promise = new Promise((resolve, reject) => {
        if (req.method !== "POST") {
            resolve({});
            return;
        }
        if (req.headers["content-type"] !== "application/json") {
            resolve({});
            return;
        }
        let postData = ''
        req.on('data', chunk => {
            postData += chunk.toString()
        })
        req.on('end', () => {
            if (!postData) {
                resolve({})
            }
            resolve(JSON.parse(postData))
        })
    })
    return promise
}
const severHandle = (req, res) => {
    res.setHeader('Content-Type', 'application/json')
    const url = req.url
    req.path = url.split('?')[0]
    req.query = querystring.parse(url.split('?')[1])

    getData(req,res).then(postData=>{
        req.body=postData
        const blogRouter = handleBlogRouter(req, res);
        if (blogRouter) {
            blogRouter.then(val => {
                res.end(JSON.stringify(val))
            })
            return
        }
        res.writeHead(404,{"content-type":"text/plain"})
        res.write("404 Not Found")
        res.end()
    })
   
   
}
module.exports = severHandle